import json
import os
from PyQt6.QtWidgets import QDialog, QMessageBox

import Global
from Comm.ProxyUtil import ProxyUtil
from Comm.UploadData import UploadData
from Comm.表达式解析器 import 表达式解析器
from UI.GlobalConfig import Ui_Dialog_GlobalConfig


class GlobalConfig(QDialog, Ui_Dialog_GlobalConfig):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.config_file = "GlobalConfig.cfg"
        
        # 连接控件信号
        # self.checkBox_EnableProxy.clicked.connect(self.on_checkbox_changed)
        # self.checkBox_enableCustom.clicked.connect(self.on_checkbox_changed)
        self.radio_api.clicked.connect(self.on_radio_changed)
        self.radio_file.clicked.connect(self.on_radio_changed)
        self.btn_import.clicked.connect(self.on_import_file)
        
        # 连接保存按钮信号
        self.btn_save.clicked.connect(self.on_save_config)

        if not self.radio_api.isChecked() and not self.radio_file.isChecked():
            self.radio_api.setChecked(True)
        if not self.radio_http.isChecked() and not self.radio_socks5.isChecked():
            self.radio_http.setChecked(True)
        # 启用文件拖拽
        self.edit_filePath.setAcceptDrops(True)
        self.edit_filePath.dragEnterEvent = self._drag_enter_event
        self.edit_filePath.dropEvent = self._drop_event

        self.textEdit_Upload_Condition.setPlaceholderText(
            "请输入条件表达式(每行一个条件,支持符号:≥,>=)：\n"
            "≥4 && (A+B)≥3  #所有卡片总数大于等于4 且 A和B总数大于等于3\n"
            "A≥3 || B≥2     #A大于等于3 或者 B大于等于2\n"
            "A≥2 && B≥1     #A大于等于2 且 B大于等于1"
        )


        # 初始化界面配置
        self.load_config()
    
    def load_config(self):
        """从配置文件加载设置"""
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    
                    # 代理设置
                    self.checkBox_EnableProxy.setChecked(config.get("enable_proxy", False))
                    self.radio_api.setChecked(config.get("proxy_method", "api") == "api")
                    self.radio_file.setChecked(config.get("proxy_method", "api") == "file")
                    self.edit_apiUrl.setPlainText(config.get("api_url", ""))
                    self.edit_filePath.setText(config.get("proxy_file_path", ""))
                    self.radio_http.setChecked(config.get("api_protocol", "http") == "http")
                    self.radio_socks5.setChecked(config.get("api_protocol", "http") == "socks5")
                    self.checkBox_Show_NetIP.setChecked(config.get("show_netip", False))
                    self.checkBox_API_Repeat.setChecked(config.get("api_repeat",False))
                    
                    # 自选上传设置
                    self.checkBox_enableCustom.setChecked(config.get("enable_custom", False))
                    self.lineEdit_rolelimit.setText(str(config.get("role_limit", 1)))
                    self.edit_customUrl.setText(config.get("custom_url", ""))
                    self.edit_customParam.setPlainText(config.get("custom_param", ""))
                    self.edit_custom_table.setPlainText(config.get("custom_table", ""))
                    self.checkBox_Enable_Upload_Condition.setChecked(config.get("is_upload_condition", False))
                    self.textEdit_Upload_Condition.setPlainText(config.get("upload_condition", ""))
                    #自定义配置
                    self.edit_apiUrl.setEnabled(self.radio_api.isChecked())
                    self.edit_filePath.setEnabled(self.radio_file.isChecked())
                    self.btn_import.setEnabled(self.radio_file.isChecked())
                    self.radio_http.setEnabled(self.radio_api.isChecked())
                    self.radio_socks5.setEnabled(self.radio_api.isChecked())
                    self.checkBox_API_Repeat.setEnabled(self.radio_api.isChecked())


                    #设置
                    self.checkBox_IsRoll.setChecked(config.get("is_roll", False))
                    self.lineEdit_roll.setText(config.get("roll_id", ""))
                    self.checkBox_IsAutoBind.setChecked(config.get("is_autobind", False))
                    self.lineEdit_CDK.setText(config.get("cdk",''))
                    self.checkBox_Use_Diamond.setChecked(config.get("use_diamond",False))
                    self.checkBox_IsBattable_215.setChecked(config.get("battle_215",False))
                    self.checkBox_IsUse_Rolle_506.setChecked(config.get("roll_506", False))
                    self.checkBox_Is_Repetition_Battle.setChecked(config.get("repetition_battle", False))
                    self.checkBox_ComposeHero.setChecked(config.get('is_compose_hero', False))
                    self.lineEdit_Shop_Gold_Limit.setText(config.get('shop_gold_limit',''))
                    self.checkBox_shop.setChecked(config.get('is_shop', False))
                    
        except Exception as e:
            QMessageBox.warning(self, "警告", f"加载配置文件时出错: {str(e)}")
    
    # def on_checkbox_changed(self):
    #     """处理checkbox状态变化"""
    #     self.save_config()
        
    def on_radio_changed(self):
        """处理单选框状态变化"""
        # 根据选择的代理方式设置控件状态
        self.edit_apiUrl.setEnabled(self.radio_api.isChecked())
        self.edit_filePath.setEnabled(self.radio_file.isChecked())
        self.btn_import.setEnabled(self.radio_file.isChecked())
        self.radio_http.setEnabled(self.radio_api.isChecked())
        self.radio_socks5.setEnabled(self.radio_api.isChecked())
        self.checkBox_API_Repeat.setEnabled(self.radio_api.isChecked())
        #self.save_config()
    def save_config(self):
        """保存当前配置到文件"""
        try:
            config = {
                # 代理设置
                "enable_proxy": self.checkBox_EnableProxy.isChecked(),
                "proxy_method": "api" if self.radio_api.isChecked() else "file",
                "api_protocol": "http" if self.radio_http.isChecked() else "socket5",
                "api_url": self.edit_apiUrl.toPlainText(),
                "proxy_file_path": self.edit_filePath.text(),
                "show_netip":self.checkBox_Show_NetIP.isChecked(),
                "api_repeat":self.checkBox_API_Repeat.isChecked(),
                
                # 自选上传设置
                "enable_custom": self.checkBox_enableCustom.isChecked(),
                "role_limit": int(self.lineEdit_rolelimit.text()),
                "custom_url": self.edit_customUrl.text(),
                "custom_param": self.edit_customParam.toPlainText(),
                'custom_table':self.edit_custom_table.toPlainText(),
                'is_upload_condition':self.checkBox_Enable_Upload_Condition.isChecked(),
                'upload_condition':self.textEdit_Upload_Condition.toPlainText(),

                #设置
                "is_roll": self.checkBox_IsRoll.isChecked(),
                "roll_id": self.lineEdit_roll.text(),
                'is_autobind': self.checkBox_IsAutoBind.isChecked(),
                'cdk':self.lineEdit_CDK.text(),
                'use_diamond':self.checkBox_Use_Diamond.isChecked(),
                'battle_215':self.checkBox_IsBattable_215.isChecked(),
                'roll_506':self.checkBox_IsUse_Rolle_506.isChecked(),
                'repetition_battle':self.checkBox_Is_Repetition_Battle.isChecked(),
                'is_compose_hero':self.checkBox_ComposeHero.isChecked(),
                'shop_gold_limit':self.lineEdit_Shop_Gold_Limit.text(),
                'is_shop':self.checkBox_shop.isChecked(),
            }

            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(config, f, indent=4, ensure_ascii=False)
            Global.G_GlobalConfig= config
        except Exception as e:
            QMessageBox.warning(self, "警告", f"保存配置文件时出错: {str(e)}")
            
    def on_save_config(self):
        """保存按钮点击事件"""
        is_upload_condition = self.checkBox_Enable_Upload_Condition.isChecked()
        if is_upload_condition:
            parase = 表达式解析器()
            isSucess,error =parase.验证表达式(self.textEdit_Upload_Condition.toPlainText())
            if not isSucess:
                QMessageBox.information(self, "条件上传配置错误", f"错误信息:{error}")
                return
        self.save_config()
        UploadData._role_map=None
        QMessageBox.information(self, "提示", "配置保存成功！")
        
    def _drag_enter_event(self, event):
        """拖拽进入事件"""
        if event.mimeData().hasUrls():
            event.acceptProposedAction()
            
    def _drop_event(self, event):
        """拖拽释放事件"""
        if event.mimeData().hasUrls():
            file_path = event.mimeData().urls()[0].toLocalFile()
            if file_path.endswith('.txt'):
                self.edit_filePath.setText(file_path)
                
    def on_import_file(self):
        """导入文件按钮点击事件"""
        from PyQt6.QtWidgets import QFileDialog
        file_path, _ = QFileDialog.getOpenFileName(
            self, 
            "选择代理文件", 
            "", 
            "Text Files (*.txt)"
        )
        if file_path:
            self.edit_filePath.setText(file_path)